<!-- 数据追溯 -->
<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form style="margin-left: 5px;" :model="queryParams" label-position="right" inline ref="queryRef">

      <el-form-item :label="$t('review.cksdatarecordsPage.page.barCode')" prop="primaryCode">
        <el-input v-model="queryParams.primaryCode" :placeholder="$t('review.cksdatarecordsPage.page.barCodeInput')"
          @keyup.enter="handleQuery" clearable style="width: 250px" />
      </el-form-item>

      <el-form-item :label="$t('review.cksdatarecordsPage.page.dateTime')" prop="dateRange">
        <el-date-picker v-model="queryParams.dateRange" style="width: 360px" type="datetimerange"
          :default-time="defaultTime2" :shortcuts="shortcuts" value-format="YYYY-MM-DD HH:mm:ss" range-separator="-"
          start-placeholder="" end-placeholder=""></el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="search" @click="QueryClick">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
        <el-button type="warning" plain icon="Download" @click="handleExport">
          {{ $t('btn.export') }}
        </el-button>
      </el-form-item>

    </el-form>

    <!-- 下方内容（左侧选择工站、右侧显示表格） -->
    <el-row style="flex: 1;display: flex; ">

      <!-- 工站列表 ，选择不同工站需要切换动态表格 -->
      <el-col :span="24" :xs="24" style="display: flex;">
        <div class="vertical-options">
          <ul>
            <li v-for="option in options" :key="option.tableName"
              :class="{ 'selected': selectedValue === option.tableName }" @click="selectedValue = option.tableName">
              {{ option.notes }}
            </li>
          </ul>
        </div>
        <!-- 动态表格区域 -->
        <div class="table-container">
          <div style="flex: 1;position: relative;">
            <div class="table-fill">
              <el-table height="100%" :data="tableData" :key="selectedValue" border style="width: 100%"
                v-loading="loading">
                <el-table-column v-for="column in tableColumns" :key="column.columnName" :prop="column.columnName"
                  :label="column.languageKey ? $t(column.languageKey) : column.notes" :width="column.width || 'auto'"
                  align="center">

                  <!-- 如果选中的selectedValue是cks_data_radiator_op60 则在二维码列新增一个按钮 -->
                  <template #default="scope"
                    v-if="selectedValue == 'cks_data_radiator_op60' && column.columnName == 'mainCode'">
                    <el-button style="
                                            white-space: normal !important;
                                            word-break: break-all;
                                            line-height: 1.5;
                                            padding-top: 12px;
                                            padding-bottom: 12px;" link type="primary"
                      @click='startTempPressureChart(scope.row)' title="点击查看曲线图">
                      {{ scope.row.mainCode }}
                    </el-button>
                  </template>

                  <!-- 加工结果 -->
                  <template #default="scope" v-if="column.columnName == 'result'">
                    <el-tag :type="scope.row.result === '1' ? 'success' : 'error'" disable-transitions>
                      {{ scope.row.result === '1' ? 'OK' : 'NG' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            @pagination="handleQuery" />
        </div>
      </el-col>
    </el-row>

    <!-- 曲线图容器 弹出层 -->
    <el-dialog :title="proxy.$t('review.cksdatarecordsPage.cruvDialog.dialogTitle')+'-'+primaryCode"
      v-model="dialogVisible" width="80%" :before-close="() => { dialogVisible = false; }">

      <!-- 控制区域 -->
      <el-row :gutter="20" class="mb-4">
        <!-- 通道选择区域 -->
        <el-col :span="12">
          <el-form-item :label="proxy.$t('review.cksdatarecordsPage.cruvDialog.channelSelect')" label-width="80px">
            <el-scrollbar
              style="height: 240px; border: 1px solid var(--el-border-color); border-radius: var(--el-border-radius); padding: 10px;">
              <el-row :gutter="10">
                <el-col :span="6" v-for="channel in 24" :key="channel">
                  <el-checkbox v-model="selectedChannels" :label="channel"
                    :style="{ color: channelColors[channel - 1], marginBottom: '5px' }" @change="updateChart">
                    {{proxy.$t('review.cksdatarecordsPage.cruvDialog.channel')}}{{ channel }}
                  </el-checkbox>
                </el-col>
              </el-row>
            </el-scrollbar>
          </el-form-item>
        </el-col>

        <!-- 数据控制区域 -->
        <el-col :span="12">
          <el-form-item :label="proxy.$t('review.cksdatarecordsPage.cruvDialog.dataSeriesTitle')" label-width="120px">
            <el-checkbox-group v-model="dataTypes" @change="updateChart">
              <el-checkbox label="temperature">
                {{ proxy.$t('review.cksdatarecordsPage.cruvDialog.dataSeries.series1') }}
              </el-checkbox>
              <el-checkbox label="pressure" style="margin-right: 20px;">
                {{ proxy.$t('review.cksdatarecordsPage.cruvDialog.dataSeries.series2') }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item :label="proxy.$t('review.cksdatarecordsPage.cruvDialog.dataOpt')" label-width="120px">
            <el-button-group>
              <el-button type="primary" size="small" @click="selectAll" icon="Check">
                {{proxy.$t('review.cksdatarecordsPage.cruvDialog.dataOptList.all')}}
              </el-button>
              <el-button type="warning" size="small" @click="deselectAll" icon="Close">
                {{proxy.$t('review.cksdatarecordsPage.cruvDialog.dataOptList.clear')}}
              </el-button>
              <el-button type="success" size="small" @click="refreshChart" icon="Refresh">
                {{proxy.$t('review.cksdatarecordsPage.cruvDialog.dataOptList.refresh')}}
              </el-button>
            </el-button-group>
          </el-form-item>

          <el-form-item :label="proxy.$t('review.cksdatarecordsPage.cruvDialog.tipTitle')" label-width="120px">
            <el-alert :title="proxy.$t('review.cksdatarecordsPage.cruvDialog.tipText')" type="info" size="small"
              :closable="false" show-icon></el-alert>
          </el-form-item>

          <el-form-item :label="proxy.$t('review.cksdatarecordsPage.cruvDialog.tipChannelTitle')" label-width="120px">
            <div>
              <el-button
                @click="showPreview = true">{{proxy.$t('review.cksdatarecordsPage.cruvDialog.tipChannelBtn')}}</el-button>
              <el-image-viewer v-if="showPreview" :url-list="srcList" hide-on-click-modal="true" show-progress="false"
                :initial-index="0" @close="showPreview = false" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 图表容器 -->
      <div ref="chartContainer"
        style="width: 100%; height: 800px; border: 1px solid var(--el-border-color); border-radius: var(--el-border-radius); padding: 10px;">
      </div>

    </el-dialog>

  </div>
</template>

<script setup name="cksdatarecord">

import dayjs from 'dayjs'
import * as echarts from 'echarts';
import { getVirtualTables, getCollectDetailsData, exportCollectData, getCurveData } from '@/api/business/cksdatarecord'

const { proxy } = getCurrentInstance()

const defaultTime2 = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]

// 时间范围快捷选项
const shortcuts = [
  {
    text: proxy.$t('common.today'),
    value: () => {
      const start = new Date().setHours(0, 0, 0, 0)
      const end = new Date().setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisWeek'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisMonth'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.last3Month'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]


const queryRef = ref()
const options = ref([])
const today = dayjs()
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
  limit: 10000,
  dateRange: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  today.endOf('day').format('YYYY-MM-DD HH:mm:ss')],
  primaryCode: ''
})

// 选中的表名
const selectedValue = ref(null);

// 分页总数
const total = ref(0)

// 表格数据
const tableData = ref([])

// 表头配置
const tableColumns = ref([])

// 加载状态
const loading = ref(false)

// 曲线图弹出层显示控制
const dialogVisible = ref(false);

const srcList = [
  'static/images/postion_tag.png',
]

const showPreview = ref(false)

// 监听选中的表名变化
watch(selectedValue, (a, b) => {
  //console.log('selectedValue', selectedValue.value)
  //查询当前表格数据，动态列渲染
  if (selectedValue.value) {
    queryParams.pageNum = 1
    handleTableChange(selectedValue.value)
  }
})


function loaded() {
  getVirtualTables().then((res) => {
    // debugger
    options.value = res.data
    if (res.data.length > 0)
      selectedValue.value = res.data[0].tableName
  });
}


// 处理表切换
const handleTableChange = async (tableName) => {
  try {

    loading.value = true;
    // 表单参数
    const body = getQueryBody()
    // 这里应该是实际API调用，我们使用mock数据代替
    const tableInfo = (await getCollectDetailsData(tableName, body)).data;

    if (tableInfo) {
      tableColumns.value = tableInfo.columns
      tableData.value = tableInfo.data
      total.value = tableInfo.pagination.total
    } else {
      proxy.$modal.msgError(proxy.$t('review.cksdatarecordsPage.page.error1', { tableName: tableName }))
    }

  } catch (error) {

    proxy.$modal.msgError(proxy.$t('review.cksdatarecordsPage.page.error2') + `${error.message}`);

  } finally {

    loading.value = false;

  }
}

function getQueryBody() {
  const { dateRange, pageNum, pageSize, primaryCode } = queryParams
  const body = { pageNum, pageSize, primaryCode }
  proxy.addDateRange(body, dateRange)
  return body
}

const QueryClick = () => {
  queryParams.pageNum = 1
  handleQuery()
}

const handleQuery = () => {

  const { primaryCode, beginTime, endTime } = getQueryBody()
  const body = { primaryCode, beginTime, endTime }
  const hasValue = Object.values(body).some(value => value !== undefined && value !== null && String(value).trim() !== '')
  if (!hasValue) {
    resetTable()
    proxy.$modal.msgError(proxy.$t('review.cksdatarecordsPage.page.error3'))
    return
  }
  if (selectedValue.value)
    handleTableChange(selectedValue.value)
}


const resetTable = () => {
  tableData.value = []
  total.value = 0
}

const resetQuery = () => {
  queryParams.dateRange = []
  const date = dayjs()
  queryParams.dateRange = [date.startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  date.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
  proxy.resetForm('queryRef')
  QueryClick()
}

//导出，必须有查询条件 ，
const handleExport = async () => {
  const body1 = getQueryBody()
  const { primaryCode, beginTime, endTime } = body1
  const body = { primaryCode, beginTime, endTime }
  const hasValue = Object.values(body).some(value => value !== undefined && value !== null && String(value).trim() !== '')
  if (!hasValue) {
    proxy.$modal.msgError(proxy.$t('review.cksdatarecordsPage.page.error3'))
    return
  }
  //提交导出
  exportCollectData({ ...body });
}

// 初始化加载第一个表的数据
onMounted(() => {
  loaded()
  window.addEventListener('resize', handleResize);
  //handleTableChange(selectedTable.value)
})

// 销毁图表实例
onBeforeUnmount(() => {
  if (chart && chart.value) {
    chart.value.dispose();
  }
  window.removeEventListener('resize', handleResize);
});


//------------------------------------------charts-----------------------------------------------//
const startTempPressureChart = async (row) => {
  // chartData.value = generateMockData();
  var queryData = (await getCurveData(row.batchId, row.mainCode)).data;
  console.log('queryData', queryData);
  chartData.value = queryData;
  primaryCode.value = row['mainCode'];
  if (!chartData.value || chartData.value.length === 0) {
    proxy.$modal.msgError('No curve data found...');
    return;
  }

  processData();

  dialogVisible.value = true;

  nextTick(() => {
    initChart();
    updateChart();
  });
}

// 图表实例
let chart;
// 图表容器
const chartContainer = ref(null);
// 原始数据
const chartData = ref([]);
// 分组后的数据
const groupedData = ref({});
// 排序后的时间
const sortedTimes = ref([]);
// 选中的通道
const selectedChannels = ref(Array.from({ length: 24 }, (_, i) => i + 1));
// 选中的数据类型
const dataTypes = ref(['pressure', 'temperature']);
// 通道颜色配置（Element Plus风格）
const channelColors = [
  '#1890ff', '#52c41a', '#fa8c16', '#f5222d', '#722ed1', '#13c2c2',
  '#2f54eb', '#faad14', '#7cb305', '#f7ba1e', '#e53f71', '#722ed1',
  '#ff4d4f', '#fa8c16', '#1890ff', '#52c41a', '#fa8c16', '#f5222d',
  '#722ed1', '#13c2c2', '#2f54eb', '#faad14', '#7cb305', '#f7ba1e'
];
const primaryCode = ref([]);

// 初始化图表
const initChart = () => {
  if (chart) {
    chart.dispose();
  }
  chart = echarts.init(chartContainer.value);
};

// 处理数据
const processData = () => {
  const timeSet = new Set();
  groupedData.value = {};

  chartData.value.forEach(item => {
    const channel = item.Channel;
    if (!groupedData.value[channel]) {
      groupedData.value[channel] = [];
    }

    groupedData.value[channel].push({
      time: item.CreateTime,
      pressure: parseFloat(item.PressureChannel),
      temperature: parseFloat(item.TemperatureChannel)
    });

    timeSet.add(item.CreateTime);
  });

  // 排序时间
  sortedTimes.value = Array.from(timeSet).sort((a, b) => new Date(a) - new Date(b));
};

// 更新图表
const updateChart = () => {

  if (!chart) return;
  chart.clear();

  const series = [];

  selectedChannels.value.forEach(channel => {
    const channelData = groupedData.value[channel] || [];
    const color = channelColors[channel - 1];

    // 添加压力曲线
    if (dataTypes.value.includes('pressure')) {
      series.push({
        name: `${proxy.$t('review.cksdatarecordsPage.cruvDialog.channel')}${channel}-`+proxy.$t('review.cksdatarecordsPage.cruvDialog.dataSeries.series2'),
        type: 'line',
        data: channelData.map(item => [item.time, item.pressure]),
        symbol: 'none',
        lineStyle: {
          width: 2,
          color: color
        },
        emphasis: {
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 6
        },
        yAxisIndex: 0
      });
    }

    // 添加温度曲线
    if (dataTypes.value.includes('temperature')) {
      series.push({
        name: `Channel${channel}-`+proxy.$t('review.cksdatarecordsPage.cruvDialog.dataSeries.series1'),
        type: 'line',
        data: channelData.map(item => [item.time, item.temperature]),
        symbol: 'none',
        lineStyle: {
          width: 2,
          color: color,
          type: 'dashed'
        },
        emphasis: {
          lineStyle: { width: 3 },
          symbol: 'circle',
          symbolSize: 6
        },
        yAxisIndex: 1
      });
    }
  });

  // 图表配置
  const option = {
    backgroundColor: '#fff',
    title: {
      text: proxy.$t('review.cksdatarecordsPage.cruvDialog.dialogTitle'),
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },
    toolbox: {
      feature: {
        // dataZoom: {
        //   yAxisIndex: 'none'
        // },
        //restore: {},
        saveAsImage: {
          title:"Save Image",
          style:"cursor:pointer"
        }
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
      padding: 10,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      data: series.map(s => s.name),
      top: 45,
      left: 'center',
      type: 'scroll',
      pageIconColor: '#ccc',
      pageIconInactiveColor: '#666',
      pageTextStyle: {
        color: '#666'
      }
    },
    grid: {
      left: '3%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: sortedTimes.value,
      axisLabel: {
        rotate: 45,
        interval: 'auto',
        fontSize: 12
      },
      axisLine: {
        lineStyle: {
          color: 'var(--el-border-color)'
        }
      },
      splitLine: {
        show: false
      }
    },
    yAxis: [
      {
        type: 'value',
        name: proxy.$t('review.cksdatarecordsPage.cruvDialog.dataSeries.series1'),
        nameTextStyle: {
          color: '#1890ff'
        },
        axisLine: {
          lineStyle: {
            color: '#1890ff'
          }
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: 'var(--el-border-color)'
          }
        }
      },
      {
        type: 'value',
        name:  proxy.$t('review.cksdatarecordsPage.cruvDialog.dataSeries.series2'),
        nameTextStyle: {
          color: '#f5222d'
        },
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#f5222d'
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: series,
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: 0,
        start: 0,
        end: 100,
        height: 10,
        bottom: 5,
        borderColor: 'var(--el-border-color)',
        fillerColor: 'rgba(24, 144, 255, 0.2)'
      },
      {
        type: 'inside',
        xAxisIndex: 0
      }
    ]
  };
  chart.setOption(option);
};

// 全选通道
const selectAll = () => {
  selectedChannels.value = Array.from({ length: 24 }, (_, i) => i + 1);
  updateChart();
};

// 清空选择
const deselectAll = () => {
  selectedChannels.value = [];
  updateChart();
};

// 刷新图表
const refreshChart = () => {
  updateChart();
};

// 窗口大小变化时调整图表
const handleResize = () => {
  if (chart.value && dialogVisible.value) {
    chart.value.resize();
  }
};

</script>

<style scoped>
.app-container {
  display: flex;
  flex: 1;
  position: relative;
  box-sizing: border-box;
  flex-direction: column;
  padding-top: 10px;
  padding-bottom: 10px;
}

.vertical-options {
  height: 85vh;
  overflow: hidden;
  overflow-y: auto;
}

.vertical-options ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-wrap: nowrap;
  padding-right: 10px;
  flex-direction: column;
}

.vertical-options li {
  padding: 10px 15px;
  display: inline-block;
  background-color: white;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
  border: 1px solid #eee;
  /* 外边框 */
  white-space: nowrap;
  margin-top: 3px;
  max-width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.vertical-options li:hover {
  background-color: #f5f5f5;
  border-bottom: 1px solid #eee;
  /* 浅灰色边框 */
}

/* 最后一个li不需要底部边框 */
/* .vertical-options li:last-child {
    border-bottom: none;
} */

.vertical-options li.selected {
  background-color: #1e90ff;
  color: white;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding-bottom: 10px;
  gap: 5px;
  box-sizing: border-box;
  margin-left: 10px;
}

.table-fill {
  position: absolute;
  height: 100%;
  width: 100%;
  overflow: hidden;
}


/* 适配Element Plus的滚动条样式 */
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

/* 复选框选中样式与通道颜色一致 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: currentColor;
  border-color: currentColor;
}

/* 调整表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 15px;
}
</style>
